package com.itdong.securityconfig.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itdong.domain.User;
import com.itdong.mapper.PermissionMapper;
import com.itdong.mapper.UserMapper;
import com.itdong.securityconfig.dao.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", username);
        User user = userMapper.selectOne(userQueryWrapper);

        if (user == null){
            throw  new RuntimeException("用户不存在");
        }

        //获取这个用户的权限信息
        List<String> permissionCodeList = permissionMapper.getPermissionCodeList(user.getId());

        LoginUser loginUser = new LoginUser(user, permissionCodeList);

        return loginUser;
    }
}
